package com.baidu.web;

import com.baidu.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallBack") //服务降级处理
    public User queryById(@PathVariable("id") String username) {
        // Ribbon 地址调用是 IP和port 替换成 服务名称
        String url = "http://user-service/user/" + username;

        if ("itheima".equals(username)) {
            throw new RuntimeException("itheima");
        }


        User userMap = restTemplate.getForObject(url, User.class);
        System.out.println(userMap);

        return userMap;
    }

    // 降级方法
    public User queryByIdFallBack(String username) {
        User user = new User();
        user.setName("暂停服务");
        return user;
    }
}
